package com.smarthospital.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.smarthospital.common.Result.CodeMsg;
import com.smarthospital.common.Result.CommonException;
import com.smarthospital.entity.dto.WxResultJscode2sessionDTO;
import com.smarthospital.service.WxApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * create by sym  2021/4/24 9:21.
 */
@Slf4j
@Service
public class WxApiServiceImpl implements WxApiService {
    @Value("${wx.miniProgram.appid:wxe3f375ec3560c256}")
    private String miniProgramAppid;
    @Value("${wx.miniProgram.secret:2136c46f42166ccf3291c0f5774b850b}")
    private String miniProgramSecret;
    @Value("${wx.oa.appid:}")
    private String officialAccountAppid;
    @Value("${wx.oa.secret:}")
    private String officialAccountSecret;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * @param source  来源 0_小程序  1_公众号 默认小程序
     * @param code  微信code
     */
    @Override
    public WxResultJscode2sessionDTO jscode2session(Integer source,String code) {
        String appid ;
        String secret;
        if (Integer.valueOf(1).equals(source)) {
            appid = officialAccountAppid;
            secret = officialAccountSecret;
        }else {
            appid = miniProgramAppid;
            secret = miniProgramSecret;
        }
        String url = String.format(WxApiService.URL_jscode2session,appid,secret,code) ;
        String result_str = restTemplate.getForObject(url, String.class);
        log.info("【微信获取oppenId】 url {} out {}",url, result_str);
        WxResultJscode2sessionDTO result_jscode2session = JSONObject.parseObject(result_str,WxResultJscode2sessionDTO.class);
        if (result_jscode2session.getErrcode()!=null) {
            throw new CommonException(CodeMsg.ERROR_LOGIN,"获取oppenId出错");
        }
        return result_jscode2session;

    }


}
